DialogFragment

A fragment that displays a dialog window, floating in the foreground of its activity's window. This fragment contains a Dialog object, which it displays as appropriate based on the fragment's state. Control of the dialog (deciding when to show, hide, dismiss it) should be done through the APIs here, not with direct calls on the dialog.

Implementations should override this class and implement onViewCreated to supply the content of the dialog. Alternatively, they can override onCreateDialog to create an entirely custom dialog, such as an AlertDialog, with its own content.

Topics covered here:

  1. Lifecycle
  2. Basic Dialog
  3. Alert Dialog
  4. Selecting Between Dialog or Embedding

Lifecycle

DialogFragment does various things to keep the fragment's lifecycle driving it, instead of the Dialog. Note that dialogs are generally autonomous entities -- they are their own window, receiving their own input events, and often deciding on their own when to disappear (by receiving a back key event or the user clicking on a button).

DialogFragment needs to ensure that what is happening with the Fragment and Dialog states remains consistent. To do this, it watches for dismiss events from the dialog and takes care of removing its own state when they happen. This means you should use show, show, or showNow to add an instance of DialogFragment to your UI, as these keep track of how DialogFragment should remove itself when the dialog is dismissed.

Basic Dialog

The simplest use of DialogFragment is as a floating container for the fragment's view hierarchy. A simple implementation may look like this:

public class MyDialogFragment extends DialogFragment {
    int mNum;

    // Create a new instance of MyDialogFragment, providing "num" as an argument.
    static MyDialogFragment newInstance(int num) {
        MyDialogFragment f = new MyDialogFragment();

        // Supply num input as an argument.
        Bundle args = new Bundle();
        args.putInt("num", num);
        f.setArguments(args);

        return f;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mNum = getArguments().getInt("num");

        // Pick a style based on the num.
        int style = DialogFragment.STYLE_NORMAL, theme = 0;
        switch ((mNum-1)%6) {
            case 1: style = DialogFragment.STYLE_NO_TITLE; break;
            case 2: style = DialogFragment.STYLE_NO_FRAME; break;
            case 3: style = DialogFragment.STYLE_NO_INPUT; break;
            case 4: style = DialogFragment.STYLE_NORMAL; break;
            case 5: style = DialogFragment.STYLE_NORMAL; break;
            case 6: style = DialogFragment.STYLE_NO_TITLE; break;
            case 7: style = DialogFragment.STYLE_NO_FRAME; break;
            case 8: style = DialogFragment.STYLE_NORMAL; break;
        }
        switch ((mNum-1)%6) {
            case 4: theme = android.R.style.Theme_Holo; break;
            case 5: theme = android.R.style.Theme_Holo_Light_Dialog; break;
            case 6: theme = android.R.style.Theme_Holo_Light; break;
            case 7: theme = android.R.style.Theme_Holo_Light_Panel; break;
            case 8: theme = android.R.style.Theme_Holo_Light; break;
        }
        setStyle(style, theme);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_dialog, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // set DialogFragment title
        getDialog().setTitle("Dialog #" + mNum);
    }
}

An example showDialog() method on the Activity could be:

public void showDialog() {
    mStackLevel++;

    // DialogFragment.show() will take care of adding the fragment
    // in a transaction.  We also want to remove any currently showing
    // dialog, so make our own transaction and take care of that here.
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    Fragment prev = getSupportFragmentManager().findFragmentByTag("dialog");
    if (prev != null) {
        ft.remove(prev);
    }
    ft.addToBackStack(null);

    // Create and show the dialog.
    DialogFragment newFragment = MyDialogFragment.newInstance(mStackLevel);
    newFragment.show(ft, "dialog");
}

This removes any currently shown dialog, creates a new DialogFragment with an argument, and shows it as a new state on the back stack. When the transaction is popped, the current DialogFragment and its Dialog will be destroyed, and the previous one (if any) re-shown. Note that in this case DialogFragment will take care of popping the transaction of the Dialog that is dismissed separately from it.

Alert Dialog

Instead of (or in addition to) implementing onViewCreated to generate the view hierarchy inside of a dialog, you may implement onCreateDialog to create your own custom Dialog object.

This is most useful for creating an AlertDialog, allowing you to display standard alerts to the user that are managed by a fragment. A simple example implementation of this is:

public static class MyAlertDialogFragment extends DialogFragment {

    public static MyAlertDialogFragment newInstance(int title) {
        MyAlertDialogFragment frag = new MyAlertDialogFragment();
        Bundle args = new Bundle();
        args.putInt("title", title);
        frag.setArguments(args);
        return frag;
    }

    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {

        return new AlertDialog.Builder(getActivity())
                .setIcon(R.drawable.alert_dialog_icon)
                .setTitle(title)
                .setPositiveButton(R.string.alert_dialog_ok,
                        (dialogInterface, i) -> ((MainActivity)getActivity()).doPositiveClick())
                .setNegativeButton(R.string.alert_dialog_cancel,
                        (dialogInterface, i) -> ((MainActivity)getActivity()).doNegativeClick())
                .create();
        return super.onCreateDialog(savedInstanceState);
    }
}

The activity creating this fragment may have the following methods to show the dialog and receive results from it:

void showDialog() {
    DialogFragment newFragment = MyAlertDialogFragment.newInstance(
            R.string.alert_dialog_two_buttons_title);
    newFragment.show(getSupportFragmentManager(), "dialog");
}

public void doPositiveClick() {
    // Do stuff here.
    Log.i("MainActivity", "Positive click!");
}

public void doNegativeClick() {
    // Do stuff here.
    Log.i("MainActivity", "Negative click!");
}

Note that in this case the fragment is not placed on the back stack, it is just added as an indefinitely running fragment. Because dialogs normally are modal, this will still operate as a back stack, since the dialog will capture user input until it is dismissed. When it is dismissed, DialogFragment will take care of removing itself from its fragment manager.

Selecting Between Dialog or Embedding

A DialogFragment can still optionally be used as a normal fragment, if desired. This is useful if you have a fragment that in some cases should be shown as a dialog and others embedded in a larger UI. This behavior will normally be automatically selected for you based on how you are using the fragment, but can be customized with setShowsDialog.

For example, here is a simple dialog fragment:

public static class MyDialogFragment extends DialogFragment {
    static MyDialogFragment newInstance() {
        return new MyDialogFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // this fragment will be displayed in a dialog
        setShowsDialog(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.hello_world, container, false);
        View tv = v.findViewById(R.id.text);
        ((TextView)tv).setText("This is an instance of MyDialogFragment");
        return v;
    }
}

An instance of this fragment can be created and shown as a dialog:

void showDialog() {
    // Create the fragment and show it as a dialog.
    DialogFragment newFragment = MyDialogFragment.newInstance();
    newFragment.show(getSupportFragmentManager(), "dialog");
}

It can also be added as content in a view hierarchy:

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
DialogFragment newFragment = MyDialogFragment.newInstance();
ft.add(R.id.embedded, newFragment);
ft.commit();

Constructors

Link copied to clipboard
constructor()
Constructor used by the default FragmentFactory.
constructor(@LayoutRes contentLayoutId: Int)
Alternate constructor that can be called from your default, no argument constructor to provide a default layout that will be inflated by onCreateView.

Properties

Link copied to clipboard
Style for setStyle: don't draw any frame at all; the view hierarchy returned by onCreateView is entirely responsible for drawing the dialog.
Link copied to clipboard
Style for setStyle: like STYLE_NO_FRAME, but also disables all input to the dialog.
Link copied to clipboard
Style for setStyle: don't include a title area.
Link copied to clipboard
val STYLE_NORMAL: Int = 0
Style for setStyle: a basic, normal dialog.

Functions

Link copied to clipboard
open fun dismiss()
Dismiss the fragment and its dialog.
Link copied to clipboard
Version of dismiss that uses commitNow.
Link copied to clipboard
Return the Dialog this fragment is currently controlling.
Link copied to clipboard
Return the current value of setShowsDialog.
Link copied to clipboard
open fun getTheme(): Int
Link copied to clipboard
open fun isCancelable(): Boolean
Return the current value of setCancelable.
Link copied to clipboard
open fun onActivityCreated(@Nullable savedInstanceState: Bundle)
Called when the fragment's activity has been created and this fragment's view hierarchy instantiated.
Link copied to clipboard
open fun onAttach(@NonNull context: Context)
Called when a fragment is first attached to its context.
Link copied to clipboard
open fun onCancel(@NonNull dialog: DialogInterface)
Link copied to clipboard
open fun onCreate(@Nullable savedInstanceState: Bundle)
Called to do initial creation of a fragment.
Link copied to clipboard
open fun onCreateDialog(@Nullable savedInstanceState: Bundle): Dialog
Override to build your own custom Dialog container.
Link copied to clipboard
Remove dialog.
Link copied to clipboard
open fun onDetach()
Called when the fragment is no longer attached to its activity.
Link copied to clipboard
Link copied to clipboard
open fun onGetLayoutInflater(@Nullable savedInstanceState: Bundle): LayoutInflater
Returns the LayoutInflater used to inflate Views of this Fragment.
Link copied to clipboard
Called to ask the fragment to save its current dynamic state, so it can later be reconstructed in a new instance if its process is restarted.
Link copied to clipboard
open fun onStart()
Called when the Fragment is visible to the user.
Link copied to clipboard
open fun onStop()
Called when the Fragment is no longer started.
Link copied to clipboard
open fun onViewStateRestored(@Nullable savedInstanceState: Bundle)
Called when all saved state has been restored into the view hierarchy of the fragment.
Link copied to clipboard
Return the ComponentDialog this fragment is currently controlling.
Link copied to clipboard
Return the Dialog this fragment is currently controlling.
Link copied to clipboard
open fun setCancelable(cancelable: Boolean)
Control whether the shown Dialog is cancelable.
Link copied to clipboard
open fun setShowsDialog(showsDialog: Boolean)
Controls whether this fragment should be shown in a dialog.
Link copied to clipboard
open fun setStyle(style: Int, @StyleRes theme: Int)
Call to customize the basic appearance and behavior of the fragment's dialog.
Link copied to clipboard
open fun setupDialog(@NonNull dialog: Dialog, style: Int)
Link copied to clipboard
open fun show(@NonNull manager: FragmentManager, @Nullable tag: String)
Display the dialog, adding the fragment to the given FragmentManager.
open fun show(@NonNull transaction: FragmentTransaction, @Nullable tag: String): Int
Display the dialog, adding the fragment using an existing transaction and then committing the transaction.
Link copied to clipboard
open fun showNow(@NonNull manager: FragmentManager, @Nullable tag: String)
Display the dialog, immediately adding the fragment to the given FragmentManager.